package com.hly.musicbackground.Utils;

import com.alibaba.fastjson.JSONObject;
import com.hly.musicbackground.Final.RedisFinal;
import com.hly.musicbackground.result.Code;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Slf4j
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class RedisUtil {

    private final StringRedisTemplate stringRedisTemplate;

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(5);

    /**
     *  在redis中缓存对象，设置过期时间
     * */
    public void set(String key, Object value, Long time, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONObject.toJSONString(value), time, unit);
    }

    /**
     * 在redis中缓存对象，设置逻辑过期时间
     * */
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit){
        RedisData redisData = new RedisData();
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        redisData.setData(value);
        stringRedisTemplate.opsForValue().set(key, JSONObject.toJSONString(redisData));
    }

    /**
     * 根据id在redis缓存中查询数据，有则返回数据，若没有则查询数据库，重建缓存
     * */
    public <R, ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type,
                                          Function<ID, R> fn, Long time, TimeUnit unit){
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isNotEmpty(json)){
            return JSONObject.parseObject(json, type);
        }
        if (json != null){
            return null;
        }

        R r = fn.apply(id);

        if (r == null){
            stringRedisTemplate.opsForValue().set(key, "",
                    RedisFinal.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }

        set(key, r, time, unit);

        return r;
    }

    /**
     * 根据id在redis缓存中查询数据，逻辑没有过期则返回数据，若逻辑过期则新建线程查询数据库，重建缓存
     * */
    public <R, ID> R queryWithLogicalExpire(String keyPrefix, ID id, Class<R> type, Function<ID, R> fn, Long time, TimeUnit unit){
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);

        if (StringUtils.isEmpty(json)){
            return null;
        }

        RedisData redisData = JSONObject.parseObject(json, RedisData.class);

        R data = (R) redisData.getData();

        if (redisData.getExpireTime().isAfter(LocalDateTime.now())){
            return data;
        }

        boolean isLock = tryLock(key);

        if (isLock){
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    R r = fn.apply(id);
                    setWithLogicalExpire(key, r, time, unit);
                }catch (Exception e){
                    Code.BUSINESS_ERR("更新缓存错误");
                }finally {
                    releaseLock(key);
                }
            });
        }

        return data;
    }

    public boolean tryLock(String key){
        return tryLock(key, RedisFinal.LOCK_TTL, TimeUnit.SECONDS);
    }

    public boolean tryLock(String key, Long time){
        return tryLock(key, time ,TimeUnit.SECONDS);
    }

    public boolean tryLock(String key, Long time, TimeUnit unit){
        return stringRedisTemplate.opsForValue().setIfAbsent(RedisFinal.LOCK_KEY + key, "1", time, unit);
    }

    public boolean releaseLock(String key){
        return stringRedisTemplate.delete(RedisFinal.LOCK_KEY + key);
    }
}
